<script setup lang="ts">
import { addServerConfig, saveServerConfig } from '@/api';
import Upload from '@/components/mutiple-upload/index.vue';
import ServiceTime from '@/components/service-time/index.vue';
// import TagChecked from '@/components/tag-checked/index.vue';
import TagChecked from '@/components/week-tag-checked/index.vue';
import { useCareWay } from '@/hooks';
import { useCareStore } from '@/store';
import { checkServiceTime, transformDetailToForm, transformFormToSubmit, transformServiceTimeToFind } from '@/tools/care';
import type { CareServiceDetail, CareServiceFormState, LevelItem, MutipleType } from '@/types';
import type { SelectOption } from '@/types/option';
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { storeToRefs } from 'pinia';
import { reactive, ref } from 'vue';

const props = defineProps<{
	type?: string;
	data?: CareServiceDetail
}>();

const emit = defineEmits(['add']);

const formRef = ref();
const store = useCareStore();
const { ways, levels, tags } = storeToRefs(store);
const isEdit = ref(props.type === 'edit');
useCareWay();

const formState = reactive<CareServiceFormState>({
	name: '',
	icon: '',
	tag: [],
	levels: [],
	levelsInfo: [],
	case: []
});

const resetForm = () => {
	formRef.value?.resetFields();
	formState.levelsInfo = [];
	formState.case = [];
};

const open = ref(false);

const add = () => {
	resetForm();
	open.value = true;
	if (props.type === 'edit') {
		Object.assign(formState, transformDetailToForm(props.data));
	}
}

const addConfig = (close?: boolean) => {
	const params = transformFormToSubmit(formState);
	const req = isEdit.value ? saveServerConfig(params, props.data?.ID || 0) : addServerConfig(params);
	req.then(() => {
		if (close) {
			open.value = false;
		}
		message.success(isEdit.value ? '保存成功' : '添加成功');
		emit('add');
	});
};

const rules = reactive<Record<string, Rule[]>>({
	name: [{ required: true, message: '请输入服务名称' }],
	icon: [{ required: true, message: '请上传服务图标' }],
	tag: [{ required: true, message: '请选择服务标签', type: 'array', trigger: 'change' }],
});

const submit = async (close?: boolean) => {
	return formRef.value?.validate().then(() => {
		addConfig(close);
	});
}

const levelChange = (val: MutipleType[]) => {
	const selectLevels = levels.value.filter((item: SelectOption) => val.includes(item.value));
	const newLevels: LevelItem[] = [];
	for (const v of selectLevels) {
		const find = formState.levelsInfo.find((item: LevelItem) => item.id === v.value);
		const serviceTimeJson = transformServiceTimeToFind(find);
		newLevels.push({
			id: v.value,
			label: v.label,
			way: find?.way || [],
			desc: find?.desc || '',
			serviceTime: serviceTimeJson,
			...serviceTimeJson
		});
	}
	formState.levelsInfo = newLevels;
};

const resetAndSubmit = () => {
	submit().then(() => {
		resetForm();
	});
};

const cancel = () => {
	open.value = false;
	resetForm();
};

</script>

<template>
	<span @click="add">
		<slot>
			<a-button type="primary">+ 添加服务项</a-button>
		</slot>
	</span>
	<a-drawer :closable="false" size="large" v-model:open="open" placement="right">
		<a-form :rules="rules" :model="formState" ref="formRef">
			<a-form-item label="服务名称" name="name">
				<a-input placeholder="请输入服务项名称" v-model:value="formState.name"></a-input>
			</a-form-item>
			<a-form-item label="应用图标" name="icon">
				<a-input placeholder="请输入应用图标名称" v-model:value="formState.icon" />
			</a-form-item>
			<a-form-item label="服务标签" name="tag">
				<TagChecked :options="tags" v-model:value="formState.tag"></TagChecked>
			</a-form-item>
			<a-form-item label="服务示例" name="case">
				<Upload v-model:value="formState.case"></Upload>
			</a-form-item>
			<a-form-item label="适用等级" name="levels">
				<a-select mode="multiple" v-model:value="formState.levels" @change="levelChange" placeholder="请选择适用等级"
					:options="levels"></a-select>
			</a-form-item>
			<div v-for="(item, index) in formState.levelsInfo" :key="item.id" class="b-top-#eee">
				<h4>{{ item.label }}</h4>
				<a-form-item label="服务方式" :rules="[{ required: true, message: '请选择服务方式' }]" :name="['levelsInfo', index, 'way']">
					<TagChecked :options="ways" v-model:value="item.way"></TagChecked>
				</a-form-item>
				<a-form-item label="服务要求" :rules="[{ required: true, message: '请输入对应等级的服务描述' }]" :name="['levelsInfo', index, 'desc']">
					<a-input placeholder="请输入对应等级的服务描述" v-model:value="item.desc" />
				</a-form-item>
				<a-form-item label="服务时间" :name="['levelsInfo', index, 'serviceTime']" :rules="[{ required: true, type: 'object', trigger: 'change', validator: checkServiceTime }]">
					<ServiceTime
						v-model:value="item.serviceTime"
						v-model:frequency="item.frequency"
						v-model:month="item.month"
						v-model:week="item.week"
						v-model:everyMonth="item.everyMonth"
						v-model:everyWeek="item.everyWeek"
						v-model:first="item.first"
						v-model:time="item.time"
					></ServiceTime>
				</a-form-item>
			</div>
		</a-form>
		<a-space>
			<a-button v-if="props.type === 'edit'" type="primary" @click="submit">保存</a-button>
			<template v-else>
				<a-button type="primary" @click="submit(true)">添加</a-button>
				<a-button type="primary" ghost @click="resetAndSubmit">提交并添加</a-button>
			</template>
			<a-button @click="cancel">取消</a-button>
		</a-space>
	</a-drawer>
</template>
<style scoped></style>
